<template>
  <van-popup v-model:show="showTop" position="top" :style="{ height: '70%' }">
    <div class="bg-[#F4F5F6] h-full flex flex-col">
      <chooseTeamNavBar :pageStack="pageStack" @clickItem="onClickStack" />
      <div class="flex flex-col mt-2 bg-white flex-auto overflow-auto">
        <template v-if="currentDprts.length > 0">
          <div
            v-for="(item, index) in currentDprts"
            :key="index"
            class="flex flex-row items-center justify-between mb-4 px-5 bg-white"
            @click="onClickItem(item, index)"
          >
            <div class="flex flex-row items-center py-3">
              <customCheckBox
                class="mr-4"
                :checked="checkStatus(item) === checkdStatus"
                :half="checkStatus(item) === checkdHalfStatus"
                @onClick="onClickCheckBox(item, index)"
              />
              <div
                class="text-white bg-yxt-blue w-10 h-10 flex justify-center items-center rounded-full mr-2"
              >
                <p>{{ item.name.slice(0, 1) }}</p>
              </div>
              <p class="text-base text-[#262626]">{{ item.name }}</p>
            </div>
            <van-icon v-if="item.children.length > 0" name="arrow" />
          </div>
        </template>

        <van-empty v-else description="暂无数据" />
      </div>

      <div class="flex flex-row justify-between bg-white px-5 py-3">
        <van-button type="default" block @click="cancelAction">取消</van-button>
        <div class="w-[50px]"></div>
        <van-button
          type="primary"
          :disabled="disableConfirmBtn"
          color="#436BFF"
          block
          @click="confirmAction"
          >确认</van-button
        >
      </div>
    </div>
  </van-popup>
</template>

<script setup>
import {
  ref,
  defineExpose,
  computed,
  defineProps,
  defineEmits,
  onMounted,
  nextTick,
  watch
} from "vue";
import chooseTeamNavBar from "./chooseTeamNavBar.vue";
import { useMyXmateStore } from "@/store";
import customCheckBox from "@/components/customCheckBox.vue";
import { showToast } from "vant";

const store = useMyXmateStore();
const showTop = ref(false);

const emits = defineEmits(["onConfirm"]);

const props = defineProps({
  selectItems: {
    type: Array,
    default: () => []
  }
});

function show() {
  showTop.value = true;
}

function hide() {
  showTop.value = false;
}

const selectArray = ref([]);

watch(
  () => props.selectItems,
  () => {
    setDefaultSelectArray();
  }
);

const pageStack = ref([]);
const currentDprt = ref(null);
const selfDprt = computed(() => store.selfDprt);

const currentDprts = computed(() => {
  if (selfDprt.value && !currentDprt.value) {
    currentDprt.value = selfDprt.value;
    pageStack.value.push(selfDprt.value);
  }
  let array = currentDprt.value?.children || [];
  return array;
});

function onClickStack(item, index) {
  currentDprt.value = item;
  pageStack.value = pageStack.value.slice(0, index + 1);
}
function onClickItem(item) {
  if (item.children.length === 0) {
    return;
  }
  pageStack.value.push(item);
  currentDprt.value = item;
}

function onClickCheckBox(item) {
  const status = indexOfArray(selectArray.value, item);
  if (status === checkdStatus) {
    selectArray.value = [];
  } else if (status === unCheckdStatus) {
    selectArray.value = [];
    selectArray.value.push(item);
  } else {
    selectArray.value = [];
  }
}

const disableConfirmBtn = computed(
  () => props.selectItems == selectArray.value && props.selectItems.length !== 0
);

function setDefaultSelectArray() {
  selectArray.value = props.selectItems;
}
function confirmAction() {
  if (selectArray.value.length === 0) {
    showToast("必须选择一个部门");
    setDefaultSelectArray();
    return;
  }
  console.log("selectArray.value", selectArray.value);
  emits("onConfirm", selectArray.value);
  hide();
}

function cancelAction() {
  setDefaultSelectArray();
  hide();
}

function checkStatus(item) {
  return indexOfArray(selectArray.value, item);
}

const checkdStatus = 1;
const unCheckdStatus = 0;
const checkdHalfStatus = 2;
function indexOfArray(tempSelectArray, item) {
  // 1 选中 0 未选中 2 半选
  if (!tempSelectArray) return unCheckdStatus;
  let selectIdArray = tempSelectArray.map(v => v.id);
  let targetId = item.id;
  if (selectIdArray.indexOf(targetId) !== -1) return checkdStatus;
  for (let i = 0; i < tempSelectArray.length; i++) {
    let targetItem = tempSelectArray[i];
    let ids = getAllSubIdArray(targetItem);
    if (ids.indexOf(targetId) !== -1) return checkdStatus;
  }
  for (const element of item.children) {
    let tempStatus = indexOfArray(tempSelectArray, element);
    if (tempStatus === checkdStatus || tempStatus === checkdHalfStatus) {
      return checkdHalfStatus;
    }
  }
  return unCheckdStatus;
}

function getAllSubIdArray(item) {
  if (!item) {
    return [];
  }
  let array = [];
  array.push(item.id);
  for (const element of item.children || []) {
    // array.push(element.id)
    let tempArr = getAllSubIdArray(element);
    array.push(...tempArr);
  }
  return array;
}

function findObjectById(data, id) {
  console.log("findObjectById", data, id);
  return null;
  if (data?.id === id) {
    return data;
  }

  if (data.children && data.children.length > 0) {
    for (let child of data.children) {
      const result = findObjectById(child, id);
      if (result) {
        return result;
      }
    }
  }
  return null;
}

defineExpose({
  show,
  hide
});
</script>

<style lang="less" scoped></style>
